package com.spring.housing1.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/*
* 用于文件上传，异步上传
* */
@Configuration
@EnableAsync
public class ThreadPollConfig {

    @Bean("asyncExecutorPool")
    public Executor threadPolls(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor=    new   ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(20);
        threadPoolTaskExecutor.setQueueCapacity(200);
//        队列等待时间
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPoolTaskExecutor >>>>");
//        拒绝策略 (也可以采用Handle的拒绝策略:不拒绝的模式)
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        等待所有线程都执行完再关闭池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//        线程被调用等待时间
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);
        return  threadPoolTaskExecutor;

    }


    public static class Handle implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
